package com.hua.fanqiemall.product.exception;

import com.hua.common.exception.BizCodeEnum;
import com.hua.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中异常处理类
 *
 * @author <LuoWeiHua>
 * @since 2021/12/19 18:08
 **/

@RestControllerAdvice(basePackages = "com.hua.fanqiemall.product.controller")
public class FanqiemallExceptionControllerAdvice {
    private static final Logger logger = LoggerFactory.getLogger(FanqiemallExceptionControllerAdvice.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        logger.error("参数格式校验异常",e);
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        logger.error("系统未知异常",throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
